#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "../share/global.h"

#include <QSettings>
#include <QMessageBox>

static uint encrypt(uint id);

RegisterDialog::RegisterDialog(QWidget *parent) :
    id(0),
    QDialog(parent),
    ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);

    connect(ui->okButton, SIGNAL(clicked()), this, SLOT(onOk()));
    init();
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

void RegisterDialog::init()
{
    id = generateUserId();
    ui->deviceIdEdit->setText(QString("%1").arg(id, 8, 16, QChar('0')).toUpper());
}

void RegisterDialog::onOk()
{
    bool ok;
    uint passport = ui->registerCodeEdit->text().toUInt(&ok, 16);

    if (ok && (encrypt(id) == passport)){
        QSettings s;
        s.setValue(USER_ID, id);
        s.setValue(PASSPORT, passport);
        setDaysCount(MY_BIRTH.daysTo(QDate(2000, 1, 1)));
        accept();
    } else
        QMessageBox::critical(this, tr("User Registration"), tr("Invalid serial number."));
}

bool RegisterDialog::registerDevice()
{
    RegisterDialog dialog;
    return dialog.exec() == QDialog::Accepted;
}

bool RegisterDialog::verifyDevice()
{
    QSettings s;
    uint userid = generateUserId();
    uint passport = s.value(PASSPORT, 0).toUInt();

    return passport && (encrypt(userid)==passport);
}

uint encrypt(uint id)
{
    QByteArray idstr = QString("%1").arg(id, 8, 16, QChar('0')).toUpper().toLatin1();
    QByteArray macdef = QByteArray(DEFAULT_MAC);
    uint encrypted = (idstr[0]+macdef[0]) % 16;
    for (int i = 1; i < 8; ++i) {
        encrypted *= 16;
        encrypted += (idstr[i]+macdef[i]) % 16;
    }
    return encrypted;
}
